package com.study.springcache.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * spring cache配置类
 */
@Configuration
public class CacheConfig {

    /**
     * redis存储的序列化配置
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        RedisCacheConfiguration rcc = RedisCacheConfiguration.defaultCacheConfig();
        // 设置过期时间
        rcc = rcc.entryTtl(Duration.ofMinutes(30));
        // StringRedisSerializer，缓存中使用该序列化key（默认的）
        rcc = rcc.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        // GenericJackson2JsonRedisSerializer, 缓存中使用该序列化value，默认是jdk的序列化
        rcc = rcc.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return rcc;
    }
}
